package com.xunwulian.web.controller.frame;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xunwulian.api.iface.MenuAPI;
import com.xunwulian.base.entity.Menu;
import com.xunwulian.base.util.PageData;
import com.xunwulian.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * 类名称：MenuController
 */
@Controller
@RequestMapping(value = "/menu")
public class MenuController extends BaseController {

    @Reference
    private MenuAPI menuAPI;

    /**
     * 显示菜单列表
     */
    @RequestMapping
    public ModelAndView list() {
        ModelAndView mv = this.getModelAndView();
        try {
            List<Menu> menuList = menuAPI.listAllParentMenu();
            mv.addObject("menuList", menuList);
            mv.setViewName("system/menu/menu_list");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 请求新增菜单页面
     */
    @RequestMapping(value = "/toAdd")
    public ModelAndView toAdd() {
        ModelAndView mv = this.getModelAndView();
        try {
            List<Menu> menuList = menuAPI.listAllParentMenu();
            mv.addObject("menuList", menuList);
            mv.setViewName("system/menu/menu_add");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 保存菜单信息
     */
    @RequestMapping(value = "/add")
    public ModelAndView add(Menu menu) {
        ModelAndView mv = this.getModelAndView();
        try {
            menu.setMENU_ID(menuAPI.findMaxId() + 1);
            String PARENT_ID = menu.getPARENT_ID();
            if (!"0".equals(PARENT_ID)) {
                // 处理菜单类型
                Menu parentMenu = menuAPI.getMenuById(Integer.valueOf(PARENT_ID));
                menu.setMENU_TYPE(parentMenu.getMENU_TYPE());
            }
            menuAPI.saveMenu(menu);
            mv.addObject("msg", "success");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            mv.addObject("msg", "failed");
        }

        mv.setViewName("save_result");
        return mv;

    }

    /**
     * 请求编辑菜单页面
     */
    @RequestMapping(value = "/toEdit")
    public ModelAndView toEdit(Integer MENU_ID) {
        ModelAndView mv = this.getModelAndView();
        try {
            Menu menu = menuAPI.getMenuById(MENU_ID);
            List<Menu> menuList = menuAPI.listAllParentMenu();
            mv.addObject("menuList", menuList);
            // TODO PD change to menu
            mv.addObject("pd", menu);
            mv.setViewName("system/menu/menu_edit");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 请求编辑菜单图标页面
     */
    @RequestMapping(value = "/toEditicon")
    public ModelAndView toEditicon(String MENU_ID) {
        ModelAndView mv = this.getModelAndView();
        try {
            PageData pd = this.getPageData();
            pd.put("MENU_ID", MENU_ID);
            mv.addObject("pd", pd);
            mv.setViewName("system/menu/menu_icon");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 保存菜单图标 (顶部菜单)
     */
    @RequestMapping(value = "/editicon")
    public ModelAndView editicon() {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        Integer menuId = (Integer) pd.get("MENU_ID");
        String menuIcon = (String) pd.get("MENU_ICON");
        try {
            menuAPI.editicon(menuId, menuIcon);
            mv.addObject("msg", "success");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            mv.addObject("msg", "failed");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 保存编辑
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit() {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        Integer menuId = (Integer) pd.get("MENU_ID");
        String menuType = (String) pd.get("MENU_TYPE");
        String PARENT_ID = pd.getString("PARENT_ID");

        Menu menu = new Menu(menuId,
                pd.getString("MENU_NAME"),
                pd.getString("MENU_URL"),
                pd.getString("PARENT_ID"),
                pd.getString("MENU_ORDER"),
                pd.getString("MENU_ICON"),
                pd.getString("MENU_TYPE")
        );

        try {
            if (StringUtils.isBlank(PARENT_ID)) {
                PARENT_ID = "0";
                pd.put("PARENT_ID", PARENT_ID);
            }
            if ("0".equals(PARENT_ID)) {
                // 处理菜单类型
                menuAPI.editType(menuId, menuType);
            }
            menuAPI.updateMenu(menu);
            mv.addObject("msg", "success");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            mv.addObject("msg", "failed");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 获取当前菜单的所有子菜单
     */
    @RequestMapping(value = "/sub")
    public void getSub(@RequestParam String MENU_ID, HttpServletResponse response) {
        try {
            List<Menu> subMenu = menuAPI.listSubMenuByParentId(MENU_ID);
            JSONArray arr = new JSONArray(subMenu);
            PrintWriter out;
            response.setCharacterEncoding("utf-8");
            out = response.getWriter();
            String json = arr.toString();
            out.write(json);
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    /**
     * 删除菜单
     *
     */
    @RequestMapping(value = "/del")
    public void delete(@RequestParam Integer MENU_ID, PrintWriter out) {
        try {
            menuAPI.deleteMenuById(MENU_ID);
            out.write("success");
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }
}
